﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using FileManager;

namespace DalatCooking.Core.Web.HttpHandlers
{
    public class FileUploadHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");

            string _uploadFolder = "";
            if (context.Request["folder"] != null)
            {
                _uploadFolder = context.Request["folder"];
            }
            else
            {
               _uploadFolder = Setting.String("FILE_FILEFOLDER");
            }
           // string _imageResizedPath = Setting.String("FILE_FILEFOLDER");
            string errMess = "";
            string path = "";
         

          
            UploadHandler upload = new UploadHandler();

            upload.AllowedExtensions = Setting.String("FILE_ALLOW_IMAGEEXT");
            upload.GenerateUniqueFileName = Setting.Boolean("FILE_ALLOW_UNIQUENAME");

            upload.VirtualSavePath = _uploadFolder;
            upload.FileContentLenght = Setting.Int("FILE_MAXSIZE");
            upload.OverwriteExistingFile = Setting.Boolean("FILE_ALLOW_OVERWRITE");
            upload.GenerateDateFolder = Setting.Boolean("FILE_ALLOW_DATEFOLDER");
            upload.AddTextOnImage = Setting.Boolean("IMAGE_ALLOW_ADDTEXT");
            upload.ResizeImage = Setting.Boolean("IMAGE_ALLOW_RESIZE");

            int imageWidth = Setting.Int("IMAGE_WIDTH");
            int imageHeight = Setting.Int("IMAGE_HEIGHT"); 

            HttpPostedFile postedFile = context.Request.Files[0];
            // Upload Images
            if (upload.UploadFile(postedFile, ref errMess, ref path) == true)
            {
                // Copy file to Resize
                // FileHelper.CopyFile(context.Server.MapPath(path), context.Server.MapPath(_imageResizedPath));
                // Crop Image
                // string fileToResize = context.Server.MapPath(_imageResizedPath + "/" + errMess);
                //  Imaging.ResizeImage(fileToResize, 105);
                // Imaging.ResizeImage(fileToResize, fileToResize, 105, System.Drawing.Imaging.ImageFormat.Png);
                // string fileResized = _imageResizedPath + "/" + errMess;
                Uri uriSiteRoot = new Uri(context.Request.Url.GetLeftPart(UriPartial.Authority));
                var output = string.Format("{0}{1}", "", path);
                context.Response.ContentType = "text/plain";
                context.Response.Write(output);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
